import taskService from "@/api/services/taskService";
import type { TaskItem } from "@/api/services/taskService";
import { IconButton } from "@/components/icon";
import { Iconify } from "@/components/icon";
import {
	Button,
	Card,
	Space,
	Table,
	Tag,
	Tooltip,
	Typography,
	message,
	Input,
	Select,
	Form,
	Row,
	Col,
	Image,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import TaskModal from "./task-modal";

const statusMap = {
	0: { text: "暂停", color: "warning" },
	1: { text: "进行中", color: "success" },
};

export default function TaskListPage() {
	const [loading, setLoading] = useState(false);
	const [tasks, setTasks] = useState<TaskItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modalVisible, setModalVisible] = useState(false);
	const [editingTask, setEditingTask] = useState<TaskItem | undefined>();
	const [searchForm] = Form.useForm();
	const [categories, setCategories] = useState<
		{ label: string; value: number }[]
	>([]);

	// 获取任务类别列表
	const fetchCategories = async () => {
		try {
			const res = await taskService.categoryList({ page: 1, limit: 100 });
			const options = res.items.map((item) => ({
				label: item.name,
				value: item.id,
			}));
			setCategories(options);
		} catch (error) {
			console.error("获取任务类别失败:", error);
		}
	};

	useEffect(() => {
		fetchCategories();
		fetchTasks(currentPage, pageSize);
	}, [currentPage, pageSize]);

	const fetchTasks = async (page = 1, limit = 10) => {
		setLoading(true);
		try {
			const values = await searchForm.validateFields();
			console.log(values);
			const params = {
				page,
				limit,
			};
			if (values.title) {
				params.title = values.title;
			}
			if (values.status !== "") {
				params.status = values.status;
			}
			if (values.category_id !== 0) {
				params.category_id = values.category_id;
			}
			const res = await taskService.taskList(params);
			setTasks(res.items);
			setTotal(res.total);
		} catch (error) {
			message.error("获取任务列表失败");
		} finally {
			setLoading(false);
		}
	};

	const handleAddTask = () => {
		setEditingTask(undefined);
		setModalVisible(true);
	};

	const handleEditTask = async (task: TaskItem) => {
		try {
			const taskDetail = await taskService.taskInfo(task.id);
			setEditingTask(taskDetail);
			setModalVisible(true);
		} catch (error) {
			message.error("获取任务详情失败");
		}
	};

	const handleToggleStatus = async (task: TaskItem) => {
		try {
			await taskService.taskChangeStatus(task.id, task.status === 1 ? 0 : 1);
			message.success("状态更新成功");
			fetchTasks(currentPage, pageSize);
		} catch (error) {
			message.error("状态更新失败");
		}
	};

	const handleDeleteTask = async (task: TaskItem) => {
		try {
			await taskService.taskDelete(task.id);
			message.success("删除成功");
			fetchTasks(currentPage, pageSize);
		} catch (error) {
			message.error("删除失败");
		}
	};

	const handleModalOk = async (values: any) => {
		try {
			if (editingTask) {
				await taskService.taskEdit({
					id: editingTask.id,
					...values,
				});
				message.success("编辑成功");
			} else {
				await taskService.taskAdd(values);
				message.success("添加成功");
			}
			setModalVisible(false);
			fetchTasks(currentPage, pageSize);
		} catch (error) {
			message.error(editingTask ? "编辑失败" : "添加失败");
		}
	};

	const handleSearch = () => {
		setCurrentPage(1);
		fetchTasks(1, pageSize);
	};

	const handleReset = () => {
		searchForm.resetFields();
		setCurrentPage(1);
		fetchTasks(1, pageSize);
	};

	const columns: ColumnsType<TaskItem> = [
		{
			title: "ID",
			dataIndex: "id",
			key: "id",
			render: (text) => <Typography.Text strong>{text}</Typography.Text>,
		},
		{
			title: "任务图片",
			dataIndex: "image",
			key: "image",
			width: 100,
			render: (image) =>
				image ? (
					<Image
						src={image}
						alt="任务图片"
						style={{
							width: 60,
							height: 60,
							objectFit: "cover",
							borderRadius: "4px",
						}}
					/>
				) : (
					"-"
				),
		},
		{
			title: "任务标题",
			dataIndex: "title",
			key: "title",
			render: (text) => <Typography.Text strong>{text}</Typography.Text>,
		},
		{
			title: "类别",
			dataIndex: ["category", "name"],
			key: "category",
			render: (text) => <Tag color="cyan">{text}</Tag>,
		},
		{
			title: "单价(元)",
			dataIndex: "price",
			key: "price",
			render: (price) => <Typography.Text>¥{price}</Typography.Text>,
		},
		{
			title: "状态",
			dataIndex: "status",
			key: "status",
			render: (status) => (
				<Tag color={statusMap[status]?.color || "default"}>
					{statusMap[status]?.text || "未知"}
				</Tag>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			key: "createtime",
			render: (time) => new Date(time * 1000).toLocaleString(),
		},
		{
			title: "操作",
			key: "action",
			render: (_, record) => (
				<Space size="middle">
					<Tooltip title="编辑">
						<IconButton
							onClick={() => handleEditTask(record)}
							style={{ color: "#1890ff" }}
						>
							<Iconify size={16} icon="mingcute:edit-line" />
						</IconButton>
					</Tooltip>
					<Tooltip title={record.status === 1 ? "暂停" : "启动"}>
						<IconButton
							onClick={() => handleToggleStatus(record)}
							style={{
								color: record.status === 1 ? "#faad14" : "#52c41a",
								backgroundColor: record.status === 1 ? "#fff7e6" : "#f6ffed",
							}}
						>
							<Iconify
								size={16}
								icon={
									record.status === 1
										? "mingcute:pause-line"
										: "mingcute:play-line"
								}
							/>
						</IconButton>
					</Tooltip>
					<Tooltip title="删除">
						<IconButton
							onClick={() => handleDeleteTask(record)}
							style={{
								color: "#ff4d4f",
								backgroundColor: "#fff1f0",
							}}
						>
							<Iconify size={16} icon="mingcute:delete-line" />
						</IconButton>
					</Tooltip>
				</Space>
			),
		},
	];

	return (
		<Card
			title="任务列表"
			extra={
				<Button type="primary" onClick={handleAddTask}>
					新增任务
				</Button>
			}
		>
			<Form form={searchForm} className="mb-6">
				<Row gutter={[24, 24]}>
					<Col xs={24} sm={12} md={8} lg={6}>
						<Form.Item name="title" label="任务标题" className="mb-0">
							<Input placeholder="请输入任务标题" allowClear />
						</Form.Item>
					</Col>
					<Col xs={24} sm={12} md={8} lg={6}>
						<Form.Item name="status" label="状态" className="mb-0">
							<Select
								style={{ width: "100%" }}
								options={[
									{ label: "全部", value: "" },
									{ label: "未审核", value: 0 },
									{ label: "已通过", value: 1 },
									{ label: "已拒绝", value: -1 },
								]}
							/>
						</Form.Item>
					</Col>
					<Col xs={24} sm={12} md={8} lg={6}>
						<Form.Item name="category_id" label="分类" className="mb-0">
							<Select
								style={{ width: "100%" }}
								placeholder="选择分类"
								options={[{ label: "全部", value: 0 }, ...categories]}
							/>
						</Form.Item>
					</Col>
					<Col xs={24} sm={12} md={8} lg={6}>
						<Form.Item className="mb-0 flex justify-end">
							<Space>
								<Button
									type="primary"
									onClick={handleSearch}
									icon={<Iconify icon="mingcute:search-line" />}
								>
									搜索
								</Button>
								<Button
									onClick={handleReset}
									icon={<Iconify icon="mingcute:refresh-line" />}
								>
									重置
								</Button>
							</Space>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			<Table<TaskItem>
				columns={columns}
				dataSource={tasks}
				rowKey="id"
				loading={loading}
				className="custom-table"
				pagination={{
					current: currentPage,
					pageSize: pageSize,
					total: total,
					showSizeChanger: true,
					showQuickJumper: true,
					showTotal: (total) => `共 ${total} 条`,
					onChange: (page, size) => {
						setCurrentPage(page);
						setPageSize(size);
					},
				}}
			/>

			<TaskModal
				open={modalVisible}
				title={editingTask ? "编辑任务" : "新增任务"}
				initialValues={editingTask}
				onOk={handleModalOk}
				onCancel={() => setModalVisible(false)}
			/>
		</Card>
	);
}
